---
title: "JPA EntityManager Class"
date: 2019-12-27
categories:
- java
- spring-jpa
tags:
---

<div id="content">
<p>
Hibernate Jpa实现EntityManager的类是SessionImpl， 程序运行时，这个类的实例 <b>不是</b> 单例的
</p>
<blockquote>
<p>
<a href="https://stackoverflow.com/questions/9370819/hibernate-entitymanager-is-it-supposed-to-be-used-as-a-singleton">https://stackoverflow.com/questions/9370819/hibernate-entitymanager-is-it-supposed-to-be-used-as-a-singleton</a>
</p>
</blockquote>
<p>
See this Article: <a href="http://www.avaje.org/jpa.html">JPA Architecture it explain it very well.</a>
</p>
<p>
In General you need a single Entity Manager per transaction. And this Entity Manager must not be used in two transactions at the same time.
</p>
<p>
Clairification: I mean, do not use a single Entity Manager for different unit of works. Typical one transaction in one unit of work, if you have different transactions of one unit of work, then you can use the same Entity Manager
</p>
<p>
If you use Spring then Spring do this handling for you if you use the @PersistenceContext annotation to inject the EntityManager. Per default Spring "bind" the the injected EntityManager (via a proxy) to the current transaction. (And the transaction is "bound" to the thread.)
</p>
<p>
@See <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa-straight">Spring Reference 13.5.2 Implementing DAOs based on plain JPA</a> - it contains a interesting paragagraph after the code examples.
</p>
<p>
Spring 程序中注入的EntityManager(Autowired)不是SessionImpl，而是工厂类的代理（org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.java），所以能保证多线程不使用相同的SessionImpl。
</p>
</div>
<div class="status" id="postamble">
<p class="date">Date: 2019-12-27</p>
<p class="author">Author: gdme1320</p>
<p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
